package com.tangyee.home_knowledge.acticity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tangyee.R;
import com.tangyee.home_knowledge.adapter.KnowsAdapter;
import com.tangyee.home_knowledge.bean.KnowledgeItem;
import com.tangyee.home_knowledge.dao.SearchRecordDAO;
import com.tangyee.home_knowledge.util.ConstantUtil;
import com.tangyee.home_knowledge.util.HttpUtil;
import com.tangyee.home_knowledge.util.KeyBoardUtil;
import com.tangyee.home_knowledge.view.SearchRecordListView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SearchKnowledgeActivity extends AppCompatActivity {

    private String requestParamValue;
    private Handler httpHandler;
    private List<KnowledgeItem> httpGetKnowledgeItem;

    // 搜索编辑区
    private EditText searchEdit;
    // 搜索栏的取消按钮(返回上一页)
    private TextView searchCancel;

    // ListView列表 & 适配器
    private ScrollView recordScrollViewParent;
    private SearchRecordListView recordListView;
    // 删除搜索记录按键
    private TextView searchClearHistory;
    private BaseAdapter recordAdapter;
    private SearchRecordDAO searchRecordDAO;
    private Cursor recordCursor;

    // 请求得到结果
    private LinearLayout requestResultParent;
    private ListView requestResultListView;
    private KnowsAdapter requestResultAdapter;

    // 请求得到结果为空
    private LinearLayout requestEmptyParent;
    private TextView emptyRemind;

    private View keyView;

    // 解决点击历史记录 item 时布局切换问题（即先显示历史再切换布局）
    private boolean isRecordItemClick = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_home_knowledge_search);

        init();
    }

    private void init(){
        initView();
        // 参数为空是显示所以的历史记录
        setRecordList("");
        setViewListener();
    }

    /**
     * 初始化
     */
    private void initView(){
        requestParamValue = "知识";
        httpGetKnowledgeItem = new ArrayList<>();

        /////// 搜索栏
        // 取消
        searchCancel = (TextView)findViewById(R.id.search_cancel);
        // 绑定搜索框EditText
        searchEdit = (EditText) findViewById(R.id.search_edit);

        ////// 历史记录
        // 历史搜索记录 = ListView显示
        recordScrollViewParent = (ScrollView) findViewById(R.id.record_listview_parent);
        recordListView = (SearchRecordListView) findViewById(R.id.search_record_listview);
        // 删除历史搜索记录按钮
        searchClearHistory = (TextView) findViewById(R.id.search_clear_history);
        searchRecordDAO = new SearchRecordDAO(this);

        /////// 请求得到结果
        requestResultParent = (LinearLayout) findViewById(R.id.request_knowledge_result_parent);
        requestResultListView = (ListView) findViewById(R.id.request_knowledge_result_listview);
        requestResultAdapter = new KnowsAdapter(this, R.layout.layout_home_knowledge_listitem, httpGetKnowledgeItem);
        requestResultListView.setAdapter(requestResultAdapter);

        ////// 请求结果为空
        requestEmptyParent = (LinearLayout) findViewById(R.id.request_knowledge_empty_parent);
        emptyRemind = (TextView) findViewById(R.id.empty_remind);

        keyView = getWindow().getDecorView();

    }

    /**
     *
     * @param tempName 为空时得到全部的历史记录，不为空根据参数关键字查找显示
     */
    private void setRecordList(String tempName){
        // 第1次进入时查询所有的历史搜索记录，并显示在listview上，并且清除历史记录按钮是可见的
        recordCursor = searchRecordDAO.queryData(tempName);
        recordAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, recordCursor, new String[] { "name" },
                new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER){
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                TextView text = (TextView) view.findViewById(android.R.id.text1);
                text.setTextColor(Color.rgb(108,107,107));
                return view;
            }
        };
        recordListView.setAdapter(recordAdapter);
        recordAdapter.notifyDataSetChanged();
        // 清除按钮的显现
        if (recordCursor.getCount() > 0) {
            searchClearHistory.setVisibility(View.VISIBLE);
        }else {
            searchClearHistory.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 设置组件的监听事件
     */
    private void setViewListener() {

        searchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //隐藏键盘
                KeyBoardUtil.hideKeyBoard(keyView);
                // 点击取消返回上一页
                onBackPressed();
            }
        });

        /**
         * "清空搜索历史"按钮
         */
        searchClearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清空数据库
                searchRecordDAO.deleteAllData();
                //searchClearHistory.setVisibility(View.INVISIBLE);
                // 模糊搜索空字符 = 显示所有的搜索历史（此时是没有搜索记录的）
                setRecordList("");
            }
        });

        /**
         * 监听输入键盘更换后的搜索按键
         * 调用时刻：点击键盘上的搜索键时
         */
        searchEdit.setOnKeyListener(new View.OnKeyListener() {
            @SuppressLint("HandlerLeak")
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // 按了键盘里的回车（搜索）
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    createHttpHandler();

                    String editText = searchEdit.getText().toString().trim();
                    // 设置 http 请求的参数
                    requestParamValue = editText;
                    if(editText.length() >= 2) {
                        // 发出 HTTP 请求，请求数据
                        loadKnowledge();

                        // 点击搜索键后，对该搜索字段在数据库是否存在进行检查（查询）
                        boolean isExist = searchRecordDAO.isExist(editText); // 去掉左右边空格
                        // 若存在，则更新位置；若不存在，则将该搜索字段保存（插入）到数据库，并作为历史搜索记录
                        if (!isExist) { // 不存在
                            Toast.makeText(SearchKnowledgeActivity.this, editText, Toast.LENGTH_SHORT).show();
                            searchRecordDAO.insertData(editText);
                        } else { // 存在
                            searchRecordDAO.deleteADate(editText);
                            searchRecordDAO.insertData(editText);
                        }
                        //setRecordList(editText);
                    }else {
                        // 不能发出请求，设置显示相应的页面
                        recordScrollViewParent.setVisibility(View.GONE);
                        requestResultParent.setVisibility(View.GONE);
                        requestEmptyParent.setVisibility(View.VISIBLE);
                        emptyRemind.setText("搜索的有效关键字不能小于2个字");
                    }

                    // 隐藏键盘
                    KeyBoardUtil.hideKeyBoard(keyView);
                }
                return false;
            }
        });

        /**
         * 搜索框的文本变化实时监听,实时改变历史搜索列表
         */
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (!isRecordItemClick) {
                    // 设置显示历史记录
                    recordScrollViewParent.setVisibility(View.VISIBLE);
                    requestResultParent.setVisibility(View.GONE);
                    requestEmptyParent.setVisibility(View.GONE);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            // 输入文本后调用该方法
            @Override
            public void afterTextChanged(Editable s) {
                // 每次输入后，模糊查询数据库 & 显示
                // 注：若搜索框为空,则模糊搜索空字符 = 显示所有的搜索历史
                String tempName = searchEdit.getText().toString().trim();
                setRecordList(tempName);

                isRecordItemClick = false;
            }
        });

        /**
         * 搜索记录列表（ListView）监听
         * 即当用户点击搜索历史里的字段后,会直接将结果当作搜索字段进行搜索
         */
        recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                recordScrollViewParent.setVisibility(View.GONE);
                isRecordItemClick = true;

                // 获取用户点击列表里的文字,并自动填充到搜索框内
                TextView textView = (TextView) view.findViewById(android.R.id.text1);
                String name = textView.getText().toString();
                searchEdit.setText(name);
                searchRecordDAO.deleteADate(name);
                searchRecordDAO.insertData(name);
                // 隐藏键盘
                KeyBoardUtil.hideKeyBoard(keyView);
                //这里跳转到相应的搜索页面结果
                Toast.makeText(SearchKnowledgeActivity.this, name, Toast.LENGTH_SHORT).show();

                requestParamValue = name;
                createHttpHandler();
                loadKnowledge();

            }
        });

        // http 请求结果的 item 的点击事件
        requestResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(SearchKnowledgeActivity.this, KnowledgeDetailActicity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("knowID", httpGetKnowledgeItem.get(i).getKnowID());
                bundle.putString("title", httpGetKnowledgeItem.get(i).getTitle());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private void createHttpHandler(){
        httpHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case ConstantUtil.SUCCESS:
                        // 设置显示相应的页面
                        recordScrollViewParent.setVisibility(View.GONE);
                        requestResultParent.setVisibility(View.VISIBLE);
                        requestEmptyParent.setVisibility(View.GONE);
                        requestResultAdapter.clear();
                        requestResultAdapter.addAll(httpGetKnowledgeItem);
                        requestResultAdapter.notifyDataSetChanged();
                        break;
                    case ConstantUtil.FINISH:
                        // 请求结果为空，设置显示相应的页面
                        recordScrollViewParent.setVisibility(View.GONE);
                        requestResultParent.setVisibility(View.GONE);
                        requestEmptyParent.setVisibility(View.VISIBLE);
                        emptyRemind.setText("没有找到相关的内容");
                        break;
                    case ConstantUtil.FALL:
                        // 请求结果为空，设置显示相应的页面
                        recordScrollViewParent.setVisibility(View.GONE);
                        requestResultParent.setVisibility(View.GONE);
                        requestEmptyParent.setVisibility(View.VISIBLE);
                        emptyRemind.setText("请求失败");
                        break;
                    default:
                        // 请求的对话框消失
                }
            }
        };
    }

    /**
     * 网络请求，加载知识详情
     */
    private void loadKnowledge(){
        /**
         * 可以开个请求的对话框
         */

        // 设置 get 请求的参数（page, pageSize）
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        params.put(ConstantUtil.searchParamName, requestParamValue + "");

        HttpUtil.sendRequest(ConstantUtil.searchKnowledgeURL, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = httpHandler.obtainMessage();
                message.what = ConstantUtil.FALL;
                httpHandler.sendMessage(message);
            }
            /**
             * 这里不在 UI 线程里面
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 使用轻量级的Gson解析得到的json
                String responseData = response.body().string();
                System.out.println(responseData);
                Type listType = new TypeToken<List<KnowledgeItem>>(){}.getType();
                Gson gson = new Gson();
                httpGetKnowledgeItem = gson.fromJson(responseData, listType);

                // 通知加载成功
                if (httpGetKnowledgeItem.size() > 0) {
                    Message message = httpHandler.obtainMessage();
                    message.what = ConstantUtil.SUCCESS;
                    httpHandler.sendMessage(message);
                }else {
                    Message message = httpHandler.obtainMessage();
                    message.what = ConstantUtil.FINISH;
                    httpHandler.sendMessage(message);
                }

            }
        });
    }

}
